//'use strict';

const iconv = require('iconv-lite');
const cheerio = require('cheerio');
const http = require('http');
const https = require('https');

//let info = '.op_caipiao_idea_hover .op_caipiao_idea_Title';
//let value = '.op_caipiao_idea_hover .op_caipiao_idea_list.op_caipiao_idea_a.c-gap-top-small.c-clearfix .op_caipiao_idea_fl';
let info = '.c-border.c-gap-bottom-small div:first-child,.c-border.c-gap-bottom-small div:nth-child(3),.c-border.c-gap-bottom-small .c-gap-top.c-gap-bottom.op_caipiao_ball.c-clearfix'
let keywords = ['双色球','福彩3d','七乐彩','超级大乐透','七星彩']

window.query = function(){
    let data = [];
    keywords.forEach(tk=>{
        data.push(new Promise(function(resolve,reject){
            http.get("http://www.baidu.com/s?wd="+iconv.encode(tk+"开奖结果查询","utf-8"),function(res){
            let html='';
            res.on('data',function(data){
                    html+=data;
                }).on('end',function(){
                    let mp_data = new Map();
                    let data = parseHtml(html);
                    if(data!=undefined&&data.length>0){
                        mp_data.set(tk,data);
                        resolve(mp_data);
                    }
                });
            });
        }));
    });
    return data;
}

function parseHtml(body)
{
    let mapInfo = [];
    let $ = cheerio.load(body);
    $(info).toArray().forEach(gp=>{
        let titleSz = "",data = [];
        gp.children.forEach(function recursion(element){
            if(element.childNodes!=undefined){
                element.childNodes.forEach(item=>{
                    if(item.tagName == "span"){
                        recursion(item);
                    }
                    else if(Object.keys(item.parent.attribs).length!=0&&item.parent.attribs["class"].toLowerCase().indexOf("caipiao_ball_blue")!=-1){
                            data.push({value:item.data,color:'blue'});
                    }
                    else if(Object.keys(item.parent.attribs).length!=0&&item.parent.attribs["class"].toLowerCase().indexOf("caipiao_ball_red")!=-1){
                            data.push({value:item.data,color:'red'});
                    }
                    else{
                        if(item.hasOwnProperty("data"))
                            titleSz += item.data.trim() + ' ';
                    }
                });
            }
            else{
                if(element.hasOwnProperty("data"))
                    titleSz += element.data.trim();
            }
        });
        if(titleSz!="")
            mapInfo.push(titleSz);
        if(data.length>0)
            mapInfo.push(data);
    });
    return mapInfo;
}

function query_data()
{
    return new Promise(function(resolve,reject){
        let cache = new Map();
        let data = window.query();
        if(data.length>0){
            data.forEach((o)=>{
                o.then(res=>{
                    if(res.size>0)
                    res.forEach((v,k)=>{
                        cache.set(k,v)
                        if(cache.size >= keywords.length){
                            resolve(cache);
                        }
                    })
                })
            });
        }
    })
}

chrome.storage.local.get("cache", function(items) {
    query_data().then(res=>{
        if(res!=undefined&&res.size>0){
            chrome.storage.local.set({"cache":(res)});
        }
        if(items!=undefined&&Object.getOwnPropertyNames(items.cache).length!=0){
            let cnt = 0,tmp;
            res.forEach((v,k)=>{
                tmp = items.cache[k].find(o=>v.indexOf(o)==-1);
                if(tmp!=undefined){
                    cnt++;
                }
            })
            chrome.browserAction.setBadgeText({text: cnt});
        }
    })
});
